import React from 'react';
import { Tag, Button } from 'antd';
import { inject, observer } from 'mobx-react';
import { WeaTableNew } from 'comsMobx';

let WeaTable = WeaTableNew.WeaTable;
import {
  WeaTop,
  WeaTab,
  WeaRightMenu,
  WeaErrorPage,
  WeaTools,
  WeaTag,
  WeaPopoverHrm,
  WeaLocaleProvider,
} from 'ecCom';
import CoworkConstant from '../util/CoworkConstant';
import * as CoworkUtil from '../util/CoworkUtil';
import { toJS } from 'mobx';

const getLabel = WeaLocaleProvider.getLabel;

/**
 * 参与的协作页面
 */
@inject('coworkHrmViewStore', 'coworkMainStore')
@observer
class Hrmview extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    // url里面传参这边接收
    const { searchHrmid } = this.props.router.location.query;
    this.props.coworkHrmViewStore.setState({ searchHrmid });
    this.props.coworkHrmViewStore.doInit({ searchHrmid });
    this.props.coworkHrmViewStore.getUserInfo(searchHrmid);
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.location.key !== nextProps.location.key) {
      const { searchHrmid } = this.props.router.location.query;
      this.props.coworkHrmViewStore.setState({ searchHrmid });
      this.props.coworkHrmViewStore.doInit({ searchHrmid });
    }
  }

  componentWillUnmount() {
    // 组件卸载时一般清理一些状态
    const { coworkHrmViewStore } = this.props;

    coworkHrmViewStore.setShowSearchAd(false);
    coworkHrmViewStore.clearFormFields();
  }

  render() {
    const { coworkHrmViewStore } = this.props;
    const {
      comsWeaTableStore,
      loading,
      form,
      conditioninfo,
      showSearchAd,
      sessionkey,
    } = coworkHrmViewStore;
    const buttonsAd = [
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@f0a3ld@search`}
        type="primary"
        onClick={this.onTabSearch}
      >
        {getLabel(197, '搜索')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@zuixws@reset`}
        type="ghost"
        onClick={this.onTabReset}
      >
        {getLabel(2022, '重置')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@8bed3c@cancel`}
        type="ghost"
        onClick={this.onTabCancel}
      >
        {getLabel(201, '取消')}
      </Button>,
    ];

    return (
      <div className="wea-cowork-collect">
        <WeaPopoverHrm
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaPopoverHrm@szltrg`}
        />

        <WeaRightMenu
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaRightMenu@cmnltf`}
          datas={this.getRightMenu()}
          onClick={this.onRightMenuClick}
        >
          <WeaTop
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaTop@1fi6zh`}
            title={getLabel(83226, '参与的协作')}
            loading={loading}
            icon={CoworkConstant.icon}
            iconBgcolor={CoworkConstant.iconBgColor}
            buttons={this.getTopButtons()}
            buttonSpace={10}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenu()}
            onDropMenuClick={this.onRightMenuClick}
          >
            <WeaTab
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaTab@bliqdc`}
              buttonsAd={buttonsAd}
              searchType={['base', 'advanced']}
              searchsBaseValue={
                form.isFormInit &&
                form.getFormParams() &&
                form.getFormParams().name
              }
              setShowSearchAd={this.setShowSearchAd}
              showSearchAd={showSearchAd}
              hideSearchAd={this.hideSearchAd}
              searchsAd={CoworkUtil.getSearchs(form, conditioninfo, () => {
                coworkHrmViewStore.setShowSearchAd(false);
                coworkHrmViewStore.doTableLoading();
              })}
              onSearch={this.onSearch}
              onSearchChange={this.onSearchChange}
            />
            <WeaTable
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaTable@zg1nkq`}
              comsWeaTableStore={comsWeaTableStore}
              loading={loading}
              sessionkey={sessionkey}
              needScroll={true}
              hasOrder={true}
              getColumns={this.getNewColumns}
            />
          </WeaTop>
        </WeaRightMenu>
      </div>
    );
  }

  setShowSearchAd = bool =>
    this.props.coworkHrmViewStore.setShowSearchAd(bool);
  hideSearchAd = () => this.props.coworkHrmViewStore.setShowSearchAd(false);
  onSearch = () => {
    const {
      coworkHrmViewStore: { searchParamsAd, doTableLoading },
    } = this.props;
    doTableLoading(searchParamsAd);
  };
  onSearchChange = v =>
    this.props.coworkHrmViewStore.appendFormFields({ name: v });

  // 右键菜单
  getRightMenu() {
    let btns = [];
    btns.push({
      key: 'search',
      icon: <i className="icon-coms-search" />,
      content: getLabel(197, '搜索'),
    });
    btns.push({
      key: 'ShowCustomColumns',
      icon: <i className="icon-coms-Custom" />,
      content: getLabel(382660, '显示定制列'),
    });
    // btns.push({ key: "help", icon: <i className='icon-coms-Custom'/>, content: '帮助' });
    return btns;
  }

  // 右键菜单事件绑定
  onRightMenuClick = (key) => {
    const { coworkHrmViewStore } = this.props;
    if (key == 'search') {
      coworkHrmViewStore.doTableLoading();
      coworkHrmViewStore.setShowSearchAd(false);
    } else if (key == 'ShowCustomColumns') {
      const { comsWeaTableStore, sessionkey } = toJS(coworkHrmViewStore);
      comsWeaTableStore.setColSetVisible(sessionkey, true);
      comsWeaTableStore.tableColSet(sessionkey, true);
    }
  };

  onTabSearch = () => {
    const { coworkHrmViewStore } = this.props;
    coworkHrmViewStore.setShowSearchAd(false);
    coworkHrmViewStore.doTableLoading();
  };
  onTabReset = () => {
    const { coworkHrmViewStore } = this.props;
    coworkHrmViewStore.clearFormFields();
  };
  onTabCancel = () => {
    const { coworkHrmViewStore } = this.props;
    coworkHrmViewStore.setShowSearchAd(false);
  };

  // 自定义过滤渲染
  getNewColumns = (columns) => {
    let newColumns = '';
    newColumns = columns.map((column) => {
      let newColumn = column;
      newColumn.render = (text, record) => {
        // 前端元素转义
        let valueSpan =
          record[`${newColumn.dataIndex}span`] !== undefined
            ? record[`${newColumn.dataIndex}span`]
            : record[newColumn.dataIndex];
        const { isMe } = this.props.coworkHrmViewStore;
        let url = '';
        if (newColumn.dataIndex == 'name') {
          let strs =
            record.id_strspan != undefined && JSON.parse(record.id_strspan);
          return (
            <div className="cowork-list-name">
              {record.approvalAtatus == '1' && (
                <span className="cowork-approval">
                  【{getLabel(2242, '待审批')}】
                </span>
              )}
              <a
                style={record.isnew == 1 ? { fontWeight: 600 } : null}
                onClick={() => {
                  window.open(CoworkUtil.getViewCoworkUrl(record.id));
                }}
              >
                {text}
              </a>
              {record.isTop == '1' && (
                <Tag
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_Tag@2rzul2`}
                  className="cowork-top"
                >
                  Top
                </Tag>
              )}
              {isMe && (
                <div style={{ display: 'block' }}>
                  {strs.length > 0 &&
                    strs.map(str => (
                      <span style={{ display: 'inline-block' }}>
                        <WeaTag
                          ecId={`${
                            (this && this.props && this.props.ecId) || ''
                          }_WeaTag@r3mjuy@${str.labelColor}`}
                          className="listview-tag"
                          color={str.labelColor}
                          closable
                          onClose={() => this.deleteTag(str, record)}
                        >
                          {str.labelName}
                        </WeaTag>
                      </span>
                    ))}
                </div>
              )}
            </div>
          );
        } else if (newColumn.dataIndex == 'floorNum') {
          url = CoworkUtil.getViewCoworkOfFloorNnmUrl(
            record.id,
            record.floorNum,
          );
        }
        return url == '' ? (
          <div
            className="wea-url"
            dangerouslySetInnerHTML={{ __html: valueSpan }}
          />
        ) : (
          <div
            className="wea-url-name"
            style={{ cursor: 'pointer' }}
            title={text}
            onClick={() => {
              window.open(url);
            }}
            dangerouslySetInnerHTML={{ __html: valueSpan }}
          />
        );
      };
      return newColumn;
    });
    return newColumns;
  };

  // 执行搜索方法（也可用于刷新table）
  executeSearch() {
    const { coworkHrmViewStore } = this.props;
    coworkHrmViewStore.setShowSearchAd(false);
    coworkHrmViewStore.doTableLoading();
  }

  // 获得table选中行的主键值数组。若没选中任何一条，返回空数组
  getTableSelectedValues() {
    const { coworkHrmViewStore } = this.props;
    const { comsWeaTableStore } = coworkHrmViewStore;
    let values = comsWeaTableStore.selectedRowKeysAllPages;
    return values;
  }

  deleteTag = (label, record) => {
    this.props.coworkMainStore.deleteCoworkLabels(label, record.id);
  };
  // top中的按钮
  getTopButtons() {
    return [];
  }
}

export default WeaTools.tryCatch(
  React,
  props => (
    <WeaErrorPage
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaErrorPage@p7vzjm`}
      msg={
        props.error
          ? props.error
          : getLabel(186, '对不起，该页面异常，请联系管理员！', 'error')
      }
    />
  ),
  { error: '' },
)(Hrmview);
